#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <vector>
#include <iostream>
enum{
  OK,
  USAGE_ERR
};

void Task()
{
  int cnt = 5;
  while(cnt--)
  {
    printf("我是一个子进程,pid:%d,ppid:%d,cnt:%d\n",getpid(),getppid(),cnt);
    sleep(1);
  }
}

void CreateChildProcess(int num,std::vector<pid_t> *subs)
{

  for(int i = 0;i < num;i++)
  {
    pid_t id = fork();
    if(id == 0)
    {
      //child
      Task();
      exit(0);
    }
    //父进程
    subs->push_back(id);
  } 
}

void WaitAllChild(const std::vector<pid_t> &subs)
{
  for(const auto &pid : subs)
  {
    int status = 0;
    pid_t rid = waitpid(pid, &status, 0);
    if(rid > 0)
    {
      printf("子进程:%d Exit,exit code: %d\n",rid,WEXITSTATUS(status));
    }
  }
}

int main(int argc, char *argv[])
{
  if(argc != 2)
  {
    std::cout<< "Usage: " << argv[0] << " process_num" << std::endl;
    exit(USAGE_ERR);
  }
  
  int num = std::stoi(argv[1]);
  std::vector<pid_t> subs;
  //创建多进程
  CreateChildProcess(num,&subs);

  //父进程
  WaitAllChild(subs);

  return OK;
}
